"""七牛云接口"""

# -*- coding: utf-8 -*-
from qiniu import Auth
from qiniu import etag
from qiniu import put_data
from qiniu import urlsafe_base64_encode

access_key = "W0oGRaBkAhrcppAbz6Nc8-q5EcXfL5vLRashY4SI"

secret_key = "tsYCBckepW4CqW0uHb9RdfDMXRDOTEpYecJAMItL"
# 要上传的空间名
bucket_name = "python-ihome"

def pic_storage(localfile):
    # 身份鉴定,构建鉴权对象
    q = Auth(access_key, secret_key)
    # 上穿得图片名称,如果簿制定则默认生成
    key = "image_py_sz.jpg"
    if not localfile:
        return None
    # 设置转码参数
    # fops = 'avthumb/mp4/s/640x360/vb/1.25m'
    # 转码时使用的队列名称
    # pipeline = 'abc'
    # 可以对转码后的文件进行使用saveas参数自定义命名,当然也可以簿制定文件会默认命名并保存在当前空间
    # saveas_key = urlsafe_base64_encode('目标Bucket_Name:自定义文件key')
    # fops = fops + '|saveas/' + saveas_key
    # 在上传策略中指定
    # policy = {
    #     "persistentOps": fops,
    #     "persistentPipeline": pipeline
    # }
    # 3600为过期时长,单位秒
    # token = q.upload_token(bucket_name, key, 3600, policy)
    token = q.upload_token(bucket_name)
    try:
        ret, info = put_data(token, key, localfile)
    except Exception as e:
        # 抛出异常给调用者
        raise e
    print(ret)
    print("-----------------------")
    print(info)
    if info.status_code != 200:
        raise Exception("上传图片到七牛云失败")

    # assert ret['key'] == key
    # assert ret['hash'] == etag(localfile)
    return ret["key"]

if __name__ == "__main__":
    file = input("请输入图片的地址")
    with open(file, "rb") as f:
        data = f.read()
        pic_storage(data)